package lab;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.lightcouch.CouchDbClient;
import org.lightcouch.Response;

import com.fasterxml.jackson.databind.ObjectMapper;

public class ChatDataSource {

    private CouchDbClient dataSource;

    private final ObjectMapper jsonMapper;

    public ChatDataSource(String configFile) {
        this.jsonMapper = new ObjectMapper();

        this.dataSource = new CouchDbClient(configFile);
        this.dataSource.design().synchronizeAllWithDb();
    }

    public void shutdown() {
        dataSource.shutdown();
    }

    public void addMessage(ChatMessage message) {
        final Response response = dataSource.save(message);
        message.setId(response.getId());
        message.setRevision(response.getRev());
    }

    public ChatMessage findById(String id, String revision) {
        return dataSource.find(ChatMessage.class, id, revision);
    }

    public List<ChatMessage> findAll() {
        return dataSource.view("_all_docs").includeDocs(true).query(ChatMessage.class);
    }

    public List<ChatMessage> findMsgAfterCounter(long counter) {
        return dataSource.view("chat/FindMsgByCounter").includeDocs(true).startKey(counter + 1).query(ChatMessage.class);
    }

    public long currentMsgId() {
        try {
            Map<String, List> response = jsonMapper.readValue(dataSource.view("chat/CurrentMsgId").reduce(true).queryForStream(), Map.class);
            return response.get("rows").size() > 0 ? dataSource.view("chat/CurrentMsgId").reduce(true).queryForLong() : 0;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void deleteMessage(ChatMessage message) {
        dataSource.remove(message);
    }
}
